package main;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import com.sun.javafx.scene.control.skin.VirtualFlow;
import constant.ChildWindowConstant;
import constant.CodeConstant;
import constant.CodeFtlConstant;
import constant.Constant;
import constant.FreeMarkerConfig;
import entity.*;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import util.DataUtils;
import util.FreeOutUtil;
import util.HttpDownloadUtil;
import util.ZipUtils;

public class MainMethod {

    public static boolean progress(Parameters parameters) {

        String projectNameVal = parameters.getProjectNameVal();
        // projectNameVal = projectNameVal.toLowerCase();

        // 首字母大写的projectNameVal
        String captureProjectNameVal = captureName(projectNameVal);

        // 所选框架
        String frameWorkVal = parameters.getFrameWorkVal();

        String jsFrameWork = parameters.getJsFrameWork();

        String clientStyle = parameters.getClientFrameWorkVal();

        String clientStyleVal = clientStyle.split("-")[0];

        String dataBasePwdVal = parameters.getDataBasePwdVal();

        String dataBaseUserNameVal = parameters.getDataBaseUserNameVal();

        String dataBaseTypeVal = parameters.getDataBaseTypeVal();

        // 表名
        String tableNameVal = parameters.getTableName();

        String outPathVal = parameters.getOutPathVal();

        // 数据库url
        String dataBaseUrlVal = parameters.getDataBaseUrl();

        // 数据库driverClass
        String dataBaseDriverClassVal = parameters.getDataBaseDriverClass();

        // 登录选择
        String loginModel = parameters.getMakeModelVal();

        // 主题
        String themeVal = parameters.getThemeVal();

        // yml文件的输出流
        Writer resourcesYmlOut = null;

        // springboot相关
        // pom文件的输出流
        Writer pomOut = null;

        // clpassPath文件的输出流
        Writer clpassPathOut = null;

        // .project文件的输出流
        Writer projectOut = null;

        // springboot的入口文件文件的输出流
        Writer mainApplicationOut = null;

        // springboot的入口测试文件文件的输出流
        Writer mainApplicationTestOut = null;

        // castutil
        Writer castUtilOut = null;

        // home.html
        Writer homeHtmlOut = null;

        // welcome.html
        Writer welcomeHtmlOut = null;

        // webMvcConfig
        Writer mvcConfigOut = null;

        // baseController
        // Writer baseControllerOut = null;

        // IBaseService
        // Writer IBaseServiceOut = null;

        // baseService
        // Writer baseServiceOut = null;

        // IBaseDao
        Writer IBaseDaoOut = null;

        // ExcelUtil
        Writer excelUtilOut = null;

        // transactionAdviceConfig
        Writer transactionAdviceConfigOut = null;

        // logback
        Writer logbackOut = null;

        // springmvc框架相关
        // mvcInterceptor
        Writer mvcInterceptorOut = null;

        // jdbc.properties
        Writer mvcJdbcPropertiesOut = null;

        // spring-mvc.xml
        Writer springMvcXmlOut = null;

        // spring-mybatis.xml
        Writer springMybatisOut = null;

        // web.xml
        Writer webXmlOut = null;

        // orgEclipseComponent
        Writer orgEclipseComponentOut = null;

        // orgEclipseComponent
        Writer manifestmfOut = null;

        // mybatisConfig
        Writer mybatisConfigOut = null;

        // 登录功能相关

        Writer userControllerOut = null;

        Writer loginHtmlOut = null;

        Writer userModelOut = null;

        Writer userMapperOut = null;

        Writer IUserServiceOut = null;

        Writer userServiceOut = null;

        Writer IUserDaoOut = null;

        // 全局异常处理
        Writer allExceptionHandlerOut = null;

        // 日志切面
        Writer logAopAspectOut = null;

        // 日志工具类
        Writer loggerUtilOut = null;

        // 生成commonEntity
        Writer commonEntityOut = null;

        // 生成pageData
        Writer pageDataOut = null;

        // 生成请求公共返回的实体bean
        Writer commonResultOut = null;

        // resultConstant
        Writer resultConstantOut = null;

        // config.js
        Writer configJsOut = null;

        // pageUtil
        Writer pageUtilOut = null;

        // swaggerConfigOut
        Writer swaggerConfigOut = null;

        try {

            // 解压
            ZipUtils.unZip(new File(Constant.modelFilesZip), Constant.modelFiles, Constant.zipPwd);

            Template userMapperTemplate = null;
            Template IUserServiceTemplate = null;
            Template userServiceTemplate = null;
            Template IUserDaoTemplate = null;

            if ("动态用户".equals(loginModel)) {

                userMapperTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.userMapper_ftl);
                userMapperTemplate.setEncoding("UTF-8");

                IUserServiceTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.IUserService_ftl);
                IUserServiceTemplate.setEncoding("UTF-8");

                userServiceTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.userService_ftl);
                userServiceTemplate.setEncoding("UTF-8");

                IUserDaoTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.IUserDao_ftl);
                IUserDaoTemplate.setEncoding("UTF-8");
            }

            // =============================================JavaBean==========================================
            // 判断当前参数配置是否为JavaBean
            String ifJavaBean = ChildWindowConstant.tableParamConfig.get(CodeConstant.paramConfigKey);

            Template commonEntityTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.commonEntity_ftl);
            commonEntityTemplate.setEncoding("UTF-8");
            Template pageDataTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.pageData_ftl);
            pageDataTemplate.setEncoding("UTF-8");

            Template entityTemplate = null;
            // 实体类的模板
            if ("JavaBean".equals(ifJavaBean)) {
                entityTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.entity_ftl);
                entityTemplate.setEncoding("UTF-8");

            }

            // =============================================JavaBean==========================================

            // ===========================公共返回类 和 config.js===========================
            Template commonResultTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.commonResult_ftl);
            commonResultTemplate.setEncoding("UTF-8");

            Template resultConstantTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.resultConstant_ftl);
            resultConstantTemplate.setEncoding("UTF-8");

            Template configJsTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.configJs_ftl);
            configJsTemplate.setEncoding("UTF-8");

            // ===========================公共返回类 和 config.js===========================

            // pageUtil
            Template pageUtilTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.pageUtil_ftl);
            pageUtilTemplate.setEncoding("UTF-8");

            Template swaggerConfigTemplate = null;

            if ("是".equals(ChildWindowConstant.commonParametersModel.getIfUseSwagger())) {
                // swagger
                swaggerConfigTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.swaggerConfig_ftl);
                swaggerConfigTemplate.setEncoding("UTF-8");
            }

            Template daoTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.dao_ftl);
            daoTemplate.setEncoding("UTF-8");

            Template IServiceTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.Iservice_ftl);
            IServiceTemplate.setEncoding("UTF-8");

            Template serviceTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.service_ftl);
            serviceTemplate.setEncoding("UTF-8");

            Template controllerTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.controller_ftl);
            controllerTemplate.setEncoding("UTF-8");

            Template sqlMapperTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.sqlMapper_ftl);
            sqlMapperTemplate.setEncoding("UTF-8");

            Template htmlTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.html_ftl);
            htmlTemplate.setEncoding("UTF-8");

            Template pomTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.pom_ftl);
            pomTemplate.setEncoding("UTF-8");

            Template classPathTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.classpath_ftl);
            classPathTemplate.setEncoding("UTF-8");

            Template projectTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.project_ftl);
            projectTemplate.setEncoding("UTF-8");

            Template castUtilTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.castutil_ftl);
            castUtilTemplate.setEncoding("UTF-8");

            Template homehtmlTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.home_ftl);
            homehtmlTemplate.setEncoding("UTF-8");

            Template welcomehtmlTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.welcome_ftl);
            welcomehtmlTemplate.setEncoding("UTF-8");

            Template baseControllerTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.baseController_ftl);
            baseControllerTemplate.setEncoding("UTF-8");

            Template IBaseServiceTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.IBaseService_ftl);
            IBaseServiceTemplate.setEncoding("UTF-8");

            Template baseServiceTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.baseService_ftl);
            baseServiceTemplate.setEncoding("UTF-8");

            Template IBaseDaoTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.IBaseDao_ftl);
            IBaseDaoTemplate.setEncoding("UTF-8");

            Template excelUtilTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.excelUtil_ftl);
            excelUtilTemplate.setEncoding("UTF-8");

            Template logbackTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.logback_ftl);
            logbackTemplate.setEncoding("UTF-8");

            Template mutiTableSqlMapperTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.MutiTableSqlMapper_ftl);
            mutiTableSqlMapperTemplate.setEncoding("UTF-8");

            Template IMutiTableDaoTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.IMutiTableDao_ftl);
            IMutiTableDaoTemplate.setEncoding("UTF-8");

            Template IMutiTableServiceTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.IMutiTableService_ftl);
            IMutiTableServiceTemplate.setEncoding("UTF-8");

            Template mutiTableServiceTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.MutiTableService_ftl);
            mutiTableServiceTemplate.setEncoding("UTF-8");

            Template mutiTableControllerTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.MutiTableController_ftl);
            mutiTableControllerTemplate.setEncoding("UTF-8");

            Template mybatisConfigTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.mybatisConfig_ftl);
            mybatisConfigTemplate.setEncoding("UTF-8");

            Template userControllerTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.userController_ftl);
            userControllerTemplate.setEncoding("UTF-8");

            Template loginHtmlTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.loginHtml_ftl);
            loginHtmlTemplate.setEncoding("UTF-8");

            Template userTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.user_ftl);
            userTemplate.setEncoding("UTF-8");

            Template allExceptionHandlerTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.allExceptionHandler_ftl);
            allExceptionHandlerTemplate.setEncoding("UTF-8");

            Template logAopAspectTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.logAopAspect_ftl);
            logAopAspectTemplate.setEncoding("UTF-8");

            Template loggerUtilTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.loggerUtil_ftl);
            loggerUtilTemplate.setEncoding("UTF-8");

            Template transactionAdviceConfigTemplate = null;
            Template mvcConfigTemplate = null;
            Template ymlTemplate = null;
            Template mainApplicationTemplate = null;
            Template mainApplicationTestTemplate = null;

            if ("springBoot".equals(frameWorkVal)) {

                transactionAdviceConfigTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.transactionAdviceConfig_ftl);
                transactionAdviceConfigTemplate.setEncoding("UTF-8");

                mvcConfigTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.mvcConfig_ftl);
                mvcConfigTemplate.setEncoding("UTF-8");

                ymlTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.applicationYml_ftl);
                ymlTemplate.setEncoding("UTF-8");

                mainApplicationTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.mainApplication_ftl);
                mainApplicationTemplate.setEncoding("UTF-8");

                mainApplicationTestTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.mainApplicationTest_ftl);
                mainApplicationTestTemplate.setEncoding("UTF-8");
            }

            Template mvcInterceptorTemplate = null;
            Template mvcJdbcPropertiesTemplate = null;
            Template mvcSpringMvcXmlTemplate = null;
            Template mvcSpringMybatisTemplate = null;
            Template webXmlTemplate = null;
            Template orgEclipseComponentTemplate = null;
            Template manifestmfTemplate = null;

            if ("ssm".equals(frameWorkVal)) {
                mvcInterceptorTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.mvcInterceptor_ftl);
                mvcInterceptorTemplate.setEncoding("UTF-8");

                mvcJdbcPropertiesTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.mvcJdbcProperties_ftl);
                mvcJdbcPropertiesTemplate.setEncoding("UTF-8");

                mvcSpringMvcXmlTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.mvcSpringMvcXml_ftl);
                mvcSpringMvcXmlTemplate.setEncoding("UTF-8");

                mvcSpringMybatisTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.mvcSpringMybatis_ftl);
                mvcSpringMybatisTemplate.setEncoding("UTF-8");

                webXmlTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.webXml_ftl);
                webXmlTemplate.setEncoding("UTF-8");

                orgEclipseComponentTemplate = FreeMarkerConfig.configuration
                        .getTemplate(CodeFtlConstant.orgEclipseComponent_ftl);
                orgEclipseComponentTemplate.setEncoding("UTF-8");

                manifestmfTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.manifestmf_ftl);
                manifestmfTemplate.setEncoding("UTF-8");

            }

            // dao,controller,service and 公共
            Map<String, Object> root = new HashMap<>();

            // 项目名称
            root.put(CodeConstant.projectName, projectNameVal);
            // 首字母大写的项目名
            root.put(CodeConstant.captureProjectName, captureProjectNameVal);
            root.put(CodeConstant.packageName, projectNameVal);

            // 框架
            root.put(CodeConstant.frameWorkVal, frameWorkVal);

            root.put(CodeConstant.jsFrameWork, jsFrameWork);

            root.put(CodeConstant.theme, themeVal);

            root.put(CodeConstant.clientStyleVal, clientStyleVal);

            // yml
            root.put(CodeConstant.dataBaseUserName, dataBaseUserNameVal);
            root.put(CodeConstant.dataBasePwd, dataBasePwdVal);
            root.put(CodeConstant.dataBaseUrl, dataBaseUrlVal);
            root.put(CodeConstant.dataBaseDriverClass, dataBaseDriverClassVal);

            // sqlMapper
            root.put(CodeConstant.dataBaseType, dataBaseTypeVal);

            root.put(CodeConstant.loginModel, loginModel);

            // 连接池
            root.put(CodeConstant.databasePool, ChildWindowConstant.commonParametersModel.getDatabasePool());

            // swagger2
            root.put(CodeConstant.ifUseSwagger, ChildWindowConstant.commonParametersModel.getIfUseSwagger());

            // --------------------
            // 设置登录用户
            setLonginUser(loginModel, root);
            // --------------------

            // 项目路径配置
            String constantDir = FreeOutUtil.setProjectName(Constant.freeOutPath_constant, projectNameVal);
            String entityDir = FreeOutUtil.setProjectName(Constant.freeOutPath_entity, projectNameVal);
            String daoDir = FreeOutUtil.setProjectName(Constant.freeOutPath_dao, projectNameVal);
            String IServiceDir = FreeOutUtil.setProjectName(Constant.freeOutPath_service, projectNameVal);
            String serviceDir = FreeOutUtil.setProjectName(Constant.freeOutPath_serviceImpl, projectNameVal);
            String controllerDir = FreeOutUtil.setProjectName(Constant.freeOutPath_controller, projectNameVal);
            // 静态资源文件，包括yml等
            String resourcesDir = FreeOutUtil.setProjectName(Constant.freeOutPath_resources, projectNameVal);

            String sqlMapperDir = null;
            String htmlDir = null;
            // 入口文件的路径
            String mainApplicationDir = null;

            // sqlMapper和html的路径
            if ("ssm".equals(frameWorkVal)) {
                sqlMapperDir = FreeOutUtil.setProjectName(Constant.freeOutPath_sqlMapper_MVC, projectNameVal);
                htmlDir = FreeOutUtil.setProjectName(Constant.freeOutPath_WEBINF_MVC, projectNameVal);
            } else if ("springBoot".equals(frameWorkVal)) {
                sqlMapperDir = FreeOutUtil.setProjectName(Constant.freeOutPath_sqlMapper, projectNameVal);
                htmlDir = FreeOutUtil.setProjectName(Constant.freeOutPath_templates, projectNameVal);
                // 入口文件的路径
                mainApplicationDir = FreeOutUtil.setProjectName(Constant.mainApplicationPath, projectNameVal);

            }
            // 测试入口文件的路径
            String mainApplicationTestDir = FreeOutUtil.setProjectName(Constant.testPath, projectNameVal);

            // pom.xml的路径 .project .classpath
            String projectDir = FreeOutUtil.setProjectName(Constant.freeOutPath, projectNameVal);

            // 工具类文件的路径
            String utilDir = FreeOutUtil.setProjectName(Constant.utilPath, projectNameVal);

            // Config的路径
            String mvcConfigDir = FreeOutUtil.setProjectName(Constant.mvcConfig, projectNameVal);

            String[] tableNameArr = new String[]{};
            // 开始数据库处理===============
            if (!"".equals(tableNameVal)) {

                tableNameArr = tableNameVal.split("#");
            }

            // 生成home页面和mvc配置文件使用
            root.put(CodeConstant.tableNameList, ChildWindowConstant.currentTableCnNameMap);

            // 多表配置模块
            if (ChildWindowConstant.tablesQueryMap.size() != 0) {

                root.put(CodeConstant.tablesQueryMap, ChildWindowConstant.tablesQueryMap);
                root.put(CodeConstant.tablesQueryEndAndCnMap, ChildWindowConstant.tablesQueryEndAndCnMap);
            }

            // 创建几个核心包
            FreeOutUtil.checkAndMakeDir(outPathVal + constantDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + entityDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + daoDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + IServiceDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + serviceDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + controllerDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + sqlMapperDir);
            FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir);

            // 如果是前后端分离，还需要额外创建${projectName}-webClient包，即前台页面包

            String webClientPath = "";
            String webClientHtmlPath = "";
            String webClientJsConfigPath = "";
            if (CodeConstant.hAdminTheme.equals(themeVal)) {

                webClientPath = FreeOutUtil.setWebClientName(Constant.webClientPath, projectNameVal);
                webClientPath = FreeOutUtil.checkAndMakeDir(outPathVal + webClientPath);

                webClientHtmlPath = FreeOutUtil.setWebClientName(Constant.webClientHtmlPath, projectNameVal);
                webClientHtmlPath = FreeOutUtil.checkAndMakeDir(outPathVal + webClientHtmlPath);

                webClientJsConfigPath = FreeOutUtil.setWebClientName(Constant.webClientJsConfigPath, projectNameVal);
                webClientJsConfigPath = FreeOutUtil.checkAndMakeDir(outPathVal + webClientJsConfigPath);
            }

            // 循环生成每个表的分层代码文件
            for (int i = 0; i < tableNameArr.length; i++) {

                String currentTableName = tableNameArr[i];

                root.put(CodeConstant.realTableName, currentTableName);

                String captureurrentTableName = captureName(tableNameArr[i]);

                // 如果是JavaBean配置
                if ("JavaBean".equals(ifJavaBean)) {
                    // bean的名称
                    root.put(CodeConstant.entityName, captureurrentTableName + "Entity");

                    List<TableNameAndType> tableNameAndTypes = ChildWindowConstant.currentTableNameAndTypes.get(currentTableName);
                    root.put(CodeConstant.entityNameAndTypes,
                            tableNameAndTypes);

                }

                root.put(CodeConstant.IDaoName, "I" + captureurrentTableName + "Dao");
                root.put(CodeConstant.IServiceName, "I" + captureurrentTableName + "Service");
                root.put(CodeConstant.serviceName, captureurrentTableName + "Service");
                root.put(CodeConstant.controllerName, captureurrentTableName + "Controller");

                root.put(CodeConstant.controllerPrefix,
                        captureurrentTableName.length() > 1
                                ? captureurrentTableName.substring(0, 1).toLowerCase()
                                + captureurrentTableName.substring(1)
                                : captureurrentTableName.substring(0, 1).toLowerCase());

                root.put(CodeConstant.tableName, captureurrentTableName);

                List<String> primaryKeyList = ChildWindowConstant.primaryKeyListMap.get(currentTableName);

                String currentTableCnName = ChildWindowConstant.currentTableCnNameMap.get(currentTableName);

                //root.put(CodeConstant.primaryKeyList, primaryKeyList);

                root.put(CodeConstant.currentTableCnName, currentTableCnName);

                // 因为主键必须设置 所以所有的条件不可能为0
                List<DatabaseModel> allColumnList = ChildWindowConstant.allColumnMsgMap.get(currentTableName);

                List<DatabaseModel> sortAllColumnList = new ArrayList<>();
                sortAllColumnList.addAll(allColumnList);

                if ("mysql".equals(dataBaseTypeVal)) {
                    sortAllColumnList.sort(new Comparator<DatabaseModel>() {

                        @Override
                        public int compare(DatabaseModel o1, DatabaseModel o2) {

                            if (o1.getWhereNo().compareTo(o2.getWhereNo()) == 0) {
                                return 0;
                            } else if (o2.getWhereNo().compareTo(o1.getWhereNo()) == 1) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    });
                } else if ("oracle".equals(dataBaseTypeVal)) {
                    sortAllColumnList.sort(new Comparator<DatabaseModel>() {

                        @Override
                        public int compare(DatabaseModel o1, DatabaseModel o2) {

                            if (o1.getWhereNo().compareTo(o2.getWhereNo()) == 0) {
                                return 0;
                            } else if (o2.getWhereNo().compareTo(o1.getWhereNo()) == 1) {
                                return 1;
                            } else {
                                return -1;
                            }
                        }
                    });
                }

                // sql条件排序使用
                root.put(CodeConstant.columnList, sortAllColumnList);

                // 页面显示使用
                List<DatabaseModel> selectColumnList = ChildWindowConstant.columnMsgMap.get(currentTableName);

                selectColumnList.sort(new Comparator<DatabaseModel>() {

                    @Override
                    public int compare(DatabaseModel o1, DatabaseModel o2) {

                        if (o1.getShowNo().compareTo(o2.getShowNo()) == 0) {
                            return 0;
                        } else if (o2.getShowNo().compareTo(o1.getShowNo()) == 1) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }
                });

                // 如果查询的个数为0 则默认查全部
                if (selectColumnList.size() == 0) {
                    selectColumnList.addAll(allColumnList);
                    root.put(CodeConstant.selectColumnList, allColumnList);
                } else {
                    // 设置的查询字段列表
                    root.put(CodeConstant.selectColumnList, selectColumnList);
                }

                List<DatabaseModel> updateColumnList = ChildWindowConstant.updateColumnMsgMap.get(currentTableName);
                // 如果没有配置更新，以初始展示的项目为准
                if (updateColumnList.size() == 0) {
                    updateColumnList.addAll(selectColumnList);
                    root.put(CodeConstant.updateColumnList, selectColumnList);
                } else {
                    root.put(CodeConstant.updateColumnList, updateColumnList);
                }

                List<DatabaseModel> queryColumnList = ChildWindowConstant.queryColumnMsgMap.get(currentTableName);
                // 如果没有配置更新，以初始展示的项目为准
                if (queryColumnList.size() == 0) {
                    root.put(CodeConstant.queryColumnList, selectColumnList);
                } else {
                    root.put(CodeConstant.queryColumnList, queryColumnList);
                }

                List<DatabaseModel> primaryKeyModelList = new ArrayList<>();
                for (String primaryKey : primaryKeyList) {

                    DatabaseModel model = new DatabaseModel();
                    model.setColumnsEng(primaryKey);
                    //设置sqlParamColumnEng
                    model.setSqlParamColumnEng(DataUtils.getSqlParam(primaryKey));
                    primaryKeyModelList.add(model);
                }

                // 遍历主键的模型list，判断在selectColumnList中存不存在,如不存在，加入
                List<DatabaseModel> selectColumnListMapper = new ArrayList<>();
                selectColumnListMapper.addAll(selectColumnList);

                for (DatabaseModel model : primaryKeyModelList) {

                    // 如果没有，添加
                    if (!selectColumnListMapper.contains(model)) {
                        selectColumnListMapper.add(model);
                    }
                    /*
                     * if (updateColumnList.contains(model)) { updateColumnList.remove(model); }
                     */
                }

                root.put(CodeConstant.primaryKeyModelList, primaryKeyModelList);
                root.put(CodeConstant.selectColumnListMapper, selectColumnListMapper);

                // 实体类输出
                Writer entityOut = null;
                Writer daoOut = null;
                Writer IServiceOut = null;
                Writer serviceOut = null;
                Writer controllerOut = null;
                Writer sqlMapperOut = null;
                Writer htmlOut = null;

                try {

                    if ("JavaBean".equals(ifJavaBean)) {
                        // dao接口的输出文件
                        entityOut = new OutputStreamWriter(
                                new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + entityDir)
                                        + captureurrentTableName + "Entity.java"),
                                "UTF-8");
                    }
                    // dao接口的输出文件
                    daoOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + daoDir) + "I"
                                    + captureurrentTableName + "Dao.java"),
                            "UTF-8");
                    // service接口的输出文件
                    IServiceOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + IServiceDir) + "I"
                                    + captureurrentTableName + "Service.java"),
                            "UTF-8");
                    // service实现类的输出文件
                    serviceOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + serviceDir)
                                    + captureurrentTableName + "Service.java"),
                            "UTF-8");
                    // controller的输出文件
                    controllerOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + controllerDir)
                                    + captureurrentTableName + "Controller.java"),
                            "UTF-8");

                    // sqlMapper.xml的输出文件
                    sqlMapperOut = new OutputStreamWriter(new FileOutputStream(
                            FreeOutUtil.checkAndMakeDir(outPathVal + sqlMapperDir) + currentTableName + "Mapper.xml"),
                            "UTF-8");

                    // 当前表html的输出文件
                    if (CodeConstant.oldTheme.equals(themeVal)) {
                        htmlOut = new OutputStreamWriter(new FileOutputStream(
                                FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir + currentTableName + "\\")
                                        + "list.html"),
                                "UTF-8");
                        // 前后端分离主题
                    } else if (CodeConstant.hAdminTheme.equals(themeVal)) {

                        htmlOut = new OutputStreamWriter(new FileOutputStream(
                                FreeOutUtil.checkAndMakeDir(webClientHtmlPath + currentTableName + "\\") + "list.html"),
                                "UTF-8");

                    }

                    // 生成每个分层的代码
                    if ("JavaBean".equals(ifJavaBean)) {
                        entityTemplate.process(root, entityOut);
                    }
                    daoTemplate.process(root, daoOut);
                    IServiceTemplate.process(root, IServiceOut);
                    serviceTemplate.process(root, serviceOut);
                    controllerTemplate.process(root, controllerOut);
                    sqlMapperTemplate.process(root, sqlMapperOut);
                    htmlTemplate.process(root, htmlOut);

                    if ("JavaBean".equals(ifJavaBean)) {
                        entityOut.flush();
                    }
                    daoOut.flush();
                    IServiceOut.flush();
                    serviceOut.flush();
                    controllerOut.flush();
                    sqlMapperOut.flush();
                    htmlOut.flush();

                } catch (IOException e) {
                    JOptionPane.showMessageDialog(Constant.frmv, "表 " + currentTableName + " 生成代码时出错！", "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                } catch (TemplateException e) {
                    JOptionPane.showMessageDialog(Constant.frmv, "解析模板文件时出错！", "错误", JOptionPane.ERROR_MESSAGE);
                    return false;
                    // 关闭所有的文件流
                } finally {

                    try {
                        if (entityOut != null) {
                            entityOut.close();
                        }
                    } catch (IOException e) {
                    }

                    try {
                        if (daoOut != null) {
                            daoOut.close();
                        }
                    } catch (IOException e) {

                    }
                    try {
                        if (IServiceOut != null) {
                            IServiceOut.close();
                        }
                    } catch (IOException e) {

                    }
                    try {
                        if (serviceOut != null) {
                            serviceOut.close();
                        }
                    } catch (IOException e) {

                    }
                    try {
                        if (controllerOut != null) {
                            controllerOut.close();
                        }
                    } catch (IOException e) {

                    }
                    try {
                        if (sqlMapperOut != null) {
                            sqlMapperOut.close();
                        }
                    } catch (IOException e) {

                    }
                    try {
                        if (htmlOut != null) {
                            htmlOut.close();
                        }
                    } catch (IOException e) {

                    }

                }

            }

            // 多表
            Template mutiTableHtmlTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.mutiTableHtml_ftl);
            mutiTableHtmlTemplate.setEncoding("UTF-8");

            Template mutiTableEntityTemplate = FreeMarkerConfig.configuration
                    .getTemplate(CodeFtlConstant.mutiTableEntity_ftl);
            mutiTableHtmlTemplate.setEncoding("UTF-8");

            // 多表配置生成文件
            for (Map.Entry<String, Map<String, TablesQueryModel>> methodEntry : ChildWindowConstant.tablesQueryMap
                    .entrySet()) {

                // 当前模块英文名
                String currentMutiEng = methodEntry.getKey();
                // 当前模块中文名
                String currentMutiCn = ChildWindowConstant.tablesQueryEndAndCnMap.get(currentMutiEng);

                root.put(CodeConstant.currentMutiEng, currentMutiEng);
                String capCurrentMutiEng = captureName(currentMutiEng);
                root.put(CodeConstant.capCurrentMutiEng, capCurrentMutiEng);

                root.put(CodeConstant.currentMutiCn, currentMutiCn);

                Map<String, TablesQueryModel> methodMap = methodEntry.getValue();

                // 方法的map
                root.put(CodeConstant.currentMethodMap, methodMap);

                Writer mutiTableSqlMapperOut = null;

                Writer IMutiTableDaoOut = null;

                Writer IMutiTableServiceOut = null;

                Writer mutiTableServiceOut = null;

                Writer mutiTableControllerOut = null;

                try {
                    mutiTableSqlMapperOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + sqlMapperDir)
                                    + capCurrentMutiEng + "MutiSqlMapper.xml"),
                            "UTF-8");
                    mutiTableSqlMapperTemplate.process(root, mutiTableSqlMapperOut);

                    IMutiTableDaoOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + daoDir) + "I"
                                    + capCurrentMutiEng + "MutiDao.java"),
                            "UTF-8");
                    IMutiTableDaoTemplate.process(root, IMutiTableDaoOut);

                    IMutiTableServiceOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + IServiceDir) + "I"
                                    + capCurrentMutiEng + "MutiService.java"),
                            "UTF-8");
                    IMutiTableServiceTemplate.process(root, IMutiTableServiceOut);

                    mutiTableServiceOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + serviceDir)
                                    + capCurrentMutiEng + "MutiService.java"),
                            "UTF-8");
                    mutiTableServiceTemplate.process(root, mutiTableServiceOut);

                    mutiTableControllerOut = new OutputStreamWriter(
                            new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + controllerDir)
                                    + capCurrentMutiEng + "MutiController.java"),
                            "UTF-8");
                    mutiTableControllerTemplate.process(root, mutiTableControllerOut);

                    mutiTableControllerOut.flush();
                    mutiTableServiceOut.flush();
                    IMutiTableServiceOut.flush();
                    IMutiTableDaoOut.flush();
                    mutiTableSqlMapperOut.flush();

                } catch (Exception e1) {
                    JOptionPane.showMessageDialog(Constant.frmv, "解析模板文件时出错！", "错误", JOptionPane.ERROR_MESSAGE);
                    return false;

                } finally {

                    try {
                        if (mutiTableControllerOut != null) {
                            mutiTableControllerOut.close();
                        }
                    } catch (IOException e) {

                    }

                    try {
                        if (mutiTableServiceOut != null) {
                            mutiTableServiceOut.close();
                        }
                    } catch (IOException e) {

                    }

                    try {
                        if (IMutiTableServiceOut != null) {
                            IMutiTableServiceOut.close();
                        }
                    } catch (IOException e) {

                    }

                    try {
                        if (IMutiTableDaoOut != null) {
                            IMutiTableDaoOut.close();
                        }
                    } catch (IOException e) {

                    }

                    try {
                        if (mutiTableSqlMapperOut != null) {
                            mutiTableSqlMapperOut.close();
                        }
                    } catch (IOException e) {

                    }
                }

                // 遍历当前模块的所有方法 一个方法对应一个entity和一个html
                for (Map.Entry<String, TablesQueryModel> method : methodMap.entrySet()) {

                    // 当前方法名
                    String methodName = method.getKey();

                    TablesQueryModel tablesQueryModel = method.getValue();

                    // 当前方法中文名
                    String methodNameCn = tablesQueryModel.getMethodName_cn();

                    // 当前方法实体名 首字母大写
                    String entityName = captureName(tablesQueryModel.getEntityName());

                    // 当前方法实体中文名
                    String entityName_cn = tablesQueryModel.getEntityName_cn();

                    List<TableFiledModel> tableFiledModels = tablesQueryModel.getTableFiledModels();

                    List<TableConditionModel> tableConditionModels = tablesQueryModel.getTableConditionModels();

                    // entity的集合
                    List<EntityFieldModel> entityFieldList = new ArrayList<>();

                    for (TableFiledModel model : tableFiledModels) {
                        EntityFieldModel entityFieldModel = new EntityFieldModel();
                        entityFieldModel.setFieldName(model.getAnotherFiledName());
                        entityFieldModel.setFieldName_cn(model.getFiledText_cn());
                        entityFieldModel.setFieldType(model.getFiledType());
                        entityFieldModel.setCompareText("");
                        entityFieldList.add(entityFieldModel);
                    }

                    for (TableConditionModel model : tableConditionModels) {
                        EntityFieldModel entityFieldModel = new EntityFieldModel();
                        entityFieldModel.setFieldName(model.getAnotherTableName() + "_" + model.getFiled_eng());
                        entityFieldModel.setFieldName_cn(model.getFiled_cn());
                        entityFieldModel.setFieldType(model.getServiceType());
                        entityFieldModel.setCompareText(model.getCompareText());

                        if (!entityFieldList.contains(entityFieldModel) && "".equals(model.getUnchangeValue())) {
                            entityFieldList.add(entityFieldModel);
                        }

                    }

                    root.put(CodeConstant.currentMutiMethodEng, methodName);
                    root.put(CodeConstant.currentMutiMethodCn, methodNameCn);

                    root.put(CodeConstant.currentMutiEntityName, entityName + "Muti");
                    root.put(CodeConstant.currentMutiEntityNameCn, entityName_cn);

                    root.put(CodeConstant.tableFiledModels, tableFiledModels);
                    root.put(CodeConstant.tableConditionModels, tableConditionModels);
                    root.put(CodeConstant.entityFiledModels, entityFieldList);

                    Writer mutiTableHtmlOut = null;
                    Writer mutiEntityOut = null;

                    try {

                        // 一个方法一个html
                        if (CodeConstant.oldTheme.equals(themeVal)) {
                            mutiTableHtmlOut = new OutputStreamWriter(new FileOutputStream(
                                    FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir + currentMutiEng + "Muti\\")
                                            + methodName + "List.html"),
                                    "UTF-8");
                        } else if (CodeConstant.hAdminTheme.equals(themeVal)) {

                            mutiTableHtmlOut = new OutputStreamWriter(new FileOutputStream(
                                    FreeOutUtil.checkAndMakeDir(webClientHtmlPath + currentMutiEng + "Muti\\")
                                            + methodName + "List.html"),
                                    "UTF-8");
                        }

                        mutiTableHtmlTemplate.process(root, mutiTableHtmlOut);

                        mutiEntityOut = new OutputStreamWriter(new FileOutputStream(
                                FreeOutUtil.checkAndMakeDir(outPathVal + entityDir) + entityName + "Muti" + ".java"),
                                "UTF-8");
                        mutiTableEntityTemplate.process(root, mutiEntityOut);

                        mutiTableHtmlOut.flush();
                        mutiEntityOut.flush();

                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(Constant.frmv, "解析模板文件时出错！", "错误", JOptionPane.ERROR_MESSAGE);
                        return false;
                    } finally {
                        try {
                            if (mutiEntityOut != null) {
                                mutiEntityOut.close();
                            }
                        } catch (IOException e) {
                        }

                        try {
                            if (mutiTableHtmlOut != null) {
                                mutiTableHtmlOut.close();
                            }
                        } catch (IOException e) {
                        }
                    }

                }

            }

            // 生成自定义实体
            getMakeEntity(outPathVal, entityDir, root);

            // 下载setting.zip文件到项目路径下
            String settingsDir = FreeOutUtil.setProjectName(Constant.freeOutPath_settings, projectNameVal);
            try {
                String realSettingDir = FreeOutUtil.checkAndMakeDir(outPathVal + settingsDir);
                File mvcSettingsZip = new File(Constant.mvcSettingsZip);
                File settingsZip = new File(Constant.settingsZip);
                if ("ssm".equals(frameWorkVal)) {
                    if (!mvcSettingsZip.exists()) {
                        mvcSettingsZip = HttpDownloadUtil.downloadFile(Constant.downMvcSettingsZipNet,
                                Constant.modelFiles);
                    }
                    ZipUtils.unZip(mvcSettingsZip, realSettingDir, Constant.zipPwd);
                }
                if ("springBoot".equals(frameWorkVal)) {
                    if (!settingsZip.exists()) {
                        settingsZip = HttpDownloadUtil.downloadFile(Constant.downSettingsZipNet, Constant.modelFiles);
                    }
                    ZipUtils.unZip(settingsZip, realSettingDir, Constant.zipPwd);
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(Constant.frmv, "生成配置文件setting时出错！可能是网络问题导致的，请重试！", "错误",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            }

            String staticDir = null;

            // 如果是old 下载static.zip文件到项目路径下
            if (CodeConstant.oldTheme.equals(themeVal)) {

                if ("ssm".equals(frameWorkVal)) {
                    staticDir = FreeOutUtil.setProjectName(Constant.freeOutPath_static_MVC, projectNameVal);
                }
                if ("springBoot".equals(frameWorkVal)) {
                    staticDir = FreeOutUtil.setProjectName(Constant.freeOutPath_static, projectNameVal);
                }
                try {
                    String realStaticDir = FreeOutUtil.checkAndMakeDir(outPathVal + staticDir);
                    File staticZip = new File(Constant.staticZip);
                    if (!staticZip.exists()) {
                        staticZip = HttpDownloadUtil.downloadFile(Constant.downStaticZipNet, Constant.modelFiles);
                    }
                    ZipUtils.unZip(staticZip, realStaticDir, Constant.zipPwd);
                    // 删除压缩包
                    // staticZip.delete();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(Constant.frmv, "生成静态资源文件时出错！可能是网络问题导致的，请重试！", "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                }

                // 如果是前后端分离响应式项目
            } else if (CodeConstant.hAdminTheme.equals(themeVal)) {

                try {
                    File webClientZip = new File(Constant.webClientZip);
                    if (!webClientZip.exists()) {
                        webClientZip = HttpDownloadUtil.downloadFile(Constant.downWebClientZipNet, Constant.modelFiles);
                    }
                    ZipUtils.unZip(webClientZip, webClientPath, Constant.zipPwd);
                    // 删除压缩包
                    // staticZip.delete();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(Constant.frmv, "生成静态资源文件时出错！可能是网络问题导致的，请重试！", "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            }

            // 如果是oracle，需要添加ojdbc支持
            if ("oracle".equals(dataBaseTypeVal)) {
                // 下载lib.zip文件到项目路径下 oracle的驱动

                String libDir = null;

                if ("ssm".equals(frameWorkVal)) {
                    libDir = FreeOutUtil.setProjectName(Constant.freeOutPath_lib_MVC, projectNameVal);
                }
                if ("springBoot".equals(frameWorkVal)) {
                    libDir = FreeOutUtil.setProjectName(Constant.freeOutPath_lib, projectNameVal);
                }

                try {
                    String realLibDir = FreeOutUtil.checkAndMakeDir(outPathVal + libDir);
                    File libZip = new File(Constant.libZip);
                    if (!libZip.exists()) {
                        libZip = HttpDownloadUtil.downloadFile(Constant.downLibZipNet, Constant.modelFiles);
                    }
                    ZipUtils.unZip(libZip, realLibDir, Constant.zipPwd);
                    // 删除压缩包
                    // libZip.delete();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(Constant.frmv, "生成静态资源文件时出错！可能是网络问题导致的，请重试！", "错误",
                            JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            }

            // pom.xml的输出流
            pomOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + projectDir) + "pom.xml"), "UTF-8");

            // 生成pom.xml
            pomTemplate.process(root, pomOut);

            // .classpath的输出流
            clpassPathOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + projectDir) + ".classpath"), "UTF-8");

            // 生成.classpath
            classPathTemplate.process(root, clpassPathOut);

            // .project的输出流
            projectOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + projectDir) + ".project"), "UTF-8");

            // 生成.project
            projectTemplate.process(root, projectOut);

            // castUtil的输出流
            castUtilOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + utilDir) + "CastUtil.java"), "UTF-8");

            // 生成 castUtil
            castUtilTemplate.process(root, castUtilOut);

            // homehtml的输出流
            if (CodeConstant.oldTheme.equals(themeVal)) {
                homeHtmlOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir) + "home.html"), "UTF-8");
            } else if (CodeConstant.hAdminTheme.equals(themeVal)) {
                homeHtmlOut = new OutputStreamWriter(new FileOutputStream(webClientHtmlPath + "home.html"), "UTF-8");
            }
            // 生成 homehtml
            homehtmlTemplate.process(root, homeHtmlOut);

            // welcomehtml的输出流
            if (CodeConstant.oldTheme.equals(themeVal)) {
                welcomeHtmlOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir) + "welcome.html"),
                        "UTF-8");
            } else if (CodeConstant.hAdminTheme.equals(themeVal)) {
                welcomeHtmlOut = new OutputStreamWriter(new FileOutputStream(webClientHtmlPath + "welcome.html"),
                        "UTF-8");
            }
            // 生成 welcomehtml
            welcomehtmlTemplate.process(root, welcomeHtmlOut);

            // baseController的输出流
            /*
             * baseControllerOut = new OutputStreamWriter(new FileOutputStream(
             * FreeOutUtil.checkAndMakeDir(outPathVal + controllerDir) +
             * "BaseController.java"), "UTF-8");
             */

            // 生成 baseController
            /* baseControllerTemplate.process(root, baseControllerOut); */

            // IBaseService的输出流
            /*
             * IBaseServiceOut = new OutputStreamWriter( new
             * FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + IServiceDir) +
             * "IBaseService.java"), "UTF-8");
             *
             * // 生成 IBaseService IBaseServiceTemplate.process(root, IBaseServiceOut);
             *
             * // baseService的输出流 baseServiceOut = new OutputStreamWriter( new
             * FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + serviceDir) +
             * "BaseService.java"), "UTF-8");
             *
             * // 生成 baseService baseServiceTemplate.process(root, baseServiceOut);
             */

            // IBaseDao的输出流
            IBaseDaoOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + daoDir) + "IBaseDao.java"), "UTF-8");

            // 生成 IBaseDao
            IBaseDaoTemplate.process(root, IBaseDaoOut);

            // excelUtil的输出流
            excelUtilOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + utilDir) + "ExcelUtil.java"),
                    "UTF-8");

            // 生成 IBaseDao
            excelUtilTemplate.process(root, excelUtilOut);

            // logback的输出流
            logbackOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + resourcesDir) + "logback.xml"),
                    "UTF-8");

            // 生成 logback
            logbackTemplate.process(root, logbackOut);

            // mybatis-config的输出流
            mybatisConfigOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + sqlMapperDir) + "mybatis-config.xml"),
                    "UTF-8");

            // 生成 mybatis-config
            mybatisConfigTemplate.process(root, mybatisConfigOut);

            // loginController的输出流
            userControllerOut = new OutputStreamWriter(new FileOutputStream(
                    FreeOutUtil.checkAndMakeDir(outPathVal + controllerDir) + "LoginController.java"), "UTF-8");

            // 生成 loginController
            userControllerTemplate.process(root, userControllerOut);

            // loginHtml的输出流
            if (CodeConstant.oldTheme.equals(themeVal)) {
                loginHtmlOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir) + "login.html"),
                        "UTF-8");
            } else if (CodeConstant.hAdminTheme.equals(themeVal)) {
                loginHtmlOut = new OutputStreamWriter(new FileOutputStream(webClientHtmlPath + "login.html"), "UTF-8");
            }

            // 生成 loginHtml
            loginHtmlTemplate.process(root, loginHtmlOut);

            // user的输出流
            userModelOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + entityDir) + "User.java"), "UTF-8");

            // 生成 user
            userTemplate.process(root, userModelOut);

            // allExceptionHandler的输出流
            allExceptionHandlerOut = new OutputStreamWriter(
                    new FileOutputStream(
                            FreeOutUtil.checkAndMakeDir(outPathVal + mvcConfigDir) + "AllExceptionHandler.java"),
                    "UTF-8");

            // 生成 allExceptionHandler
            allExceptionHandlerTemplate.process(root, allExceptionHandlerOut);

            // logAopAspect的输出流
            logAopAspectOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + mvcConfigDir) + "LogAopAspect.java"),
                    "UTF-8");

            // 生成 logAopAspect
            logAopAspectTemplate.process(root, logAopAspectOut);

            // loggerUtil的输出流
            loggerUtilOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + utilDir) + "LoggerUtil.java"),
                    "UTF-8");

            // 生成 loggerUtil
            loggerUtilTemplate.process(root, loggerUtilOut);

            // 生成 commonResult
            commonResultOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + entityDir) + "CommonResult.java"),
                    "UTF-8");

            // 生成 CommonResult
            commonResultTemplate.process(root, commonResultOut);

            // 生成 resultConstant
            resultConstantOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + constantDir) + "ResultConstant.java"),
                    "UTF-8");

            // 生成 resultConstant
            resultConstantTemplate.process(root, resultConstantOut);

            // 生成 pageUtil
            pageUtilOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + utilDir) + "PageUtil.java"), "UTF-8");

            // 生成 pageUtil
            pageUtilTemplate.process(root, pageUtilOut);

            if ("是".equals(ChildWindowConstant.commonParametersModel.getIfUseSwagger())) {
                // 生成 swaggerConfig
                swaggerConfigOut = new OutputStreamWriter(
                        new FileOutputStream(
                                FreeOutUtil.checkAndMakeDir(outPathVal + mvcConfigDir) + "SwaggerConfig.java"),
                        "UTF-8");
                // 生成 swaggerConfig
                swaggerConfigTemplate.process(root, swaggerConfigOut);
            }

            // 根据主题的不同生成的路径不同
            if (CodeConstant.oldTheme.equals(themeVal)) {
                // 生成config.js
                configJsOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + staticDir + "js\\") + "config.js"), "UTF-8");

                // 生成 config.js
                configJsTemplate.process(root, configJsOut);
            } else if (CodeConstant.hAdminTheme.equals(themeVal)) {

                // 生成config.js
                configJsOut = new OutputStreamWriter(new FileOutputStream(webClientJsConfigPath + "config.js"),
                        "UTF-8");

                // 生成 config.js
                configJsTemplate.process(root, configJsOut);

            }

            // commonEntity的输出流
            commonEntityOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + entityDir) + "CommonEntity.java"),
                    "UTF-8");

            // 生成 commonEntity
            commonEntityTemplate.process(root, commonEntityOut);

            // pageData的输出流
            pageDataOut = new OutputStreamWriter(
                    new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + entityDir) + "PageData.java"),
                    "UTF-8");

            // 生成 commonEntity
            pageDataTemplate.process(root, pageDataOut);

            // 用户登录相关
            if ("动态用户".equals(loginModel)) {

                userMapperOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + sqlMapperDir) + "loginMapper.xml"), "UTF-8");
                userMapperTemplate.process(root, userMapperOut);

                IUserServiceOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + IServiceDir) + "ILoginService.java"), "UTF-8");
                IUserServiceTemplate.process(root, IUserServiceOut);

                userServiceOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + serviceDir) + "LoginService.java"), "UTF-8");
                userServiceTemplate.process(root, userServiceOut);

                IUserDaoOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + daoDir) + "ILoginDao.java"),
                        "UTF-8");
                IUserDaoTemplate.process(root, IUserDaoOut);

            }

            if ("springBoot".equals(frameWorkVal)) {
                // application.yml的输出文件
                resourcesYmlOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + resourcesDir) + "application.yml"), "UTF-8");
                // 生成yml
                ymlTemplate.process(root, resourcesYmlOut);

                // mainApplication的输出流
                mainApplicationOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + mainApplicationDir)
                                + captureProjectNameVal + "Application.java"),
                        "UTF-8");

                // 生成 mainApplication
                mainApplicationTemplate.process(root, mainApplicationOut);

                // testApplication的输出流
                mainApplicationTestOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + mainApplicationTestDir)
                                + captureProjectNameVal + "ApplicationTests.java"),
                        "UTF-8");

                // 生成 testApplication
                mainApplicationTestTemplate.process(root, mainApplicationTestOut);

                // mvcconfig的输出流
                mvcConfigOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + mvcConfigDir) + "MvcConfig.java"),
                        "UTF-8");

                // 生成 mvcconfig
                mvcConfigTemplate.process(root, mvcConfigOut);

                // transactionAdviceConfig的输出流
                transactionAdviceConfigOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + mvcConfigDir) + "TransactionAdviceConfig.java"),
                        "UTF-8");

                // 生成 transactionAdviceConfig
                transactionAdviceConfigTemplate.process(root, transactionAdviceConfigOut);
            }

            if ("ssm".equals(frameWorkVal)) {

                String meta_infDir = FreeOutUtil.setProjectName(Constant.freeOutPath_METAINF_MVC, projectNameVal);
                // 创建meta_inf文件夹
                FreeOutUtil.checkAndMakeDir(outPathVal + meta_infDir);

                FreeOutUtil.checkAndMakeDir(outPathVal + mainApplicationTestDir);
                // mvcInterceptor的输出流
                mvcInterceptorOut = new OutputStreamWriter(
                        new FileOutputStream(
                                FreeOutUtil.checkAndMakeDir(outPathVal + mvcConfigDir) + "MVCInterceptor.java"),
                        "UTF-8");
                mvcInterceptorTemplate.process(root, mvcInterceptorOut);

                mvcJdbcPropertiesOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + resourcesDir) + "jdbc.properties"), "UTF-8");
                mvcJdbcPropertiesTemplate.process(root, mvcJdbcPropertiesOut);

                springMvcXmlOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + resourcesDir) + "spring-mvc.xml"),
                        "UTF-8");
                mvcSpringMvcXmlTemplate.process(root, springMvcXmlOut);

                springMybatisOut = new OutputStreamWriter(
                        new FileOutputStream(
                                FreeOutUtil.checkAndMakeDir(outPathVal + resourcesDir) + "spring-mybatis.xml"),
                        "UTF-8");
                mvcSpringMybatisTemplate.process(root, springMybatisOut);

                webXmlOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + htmlDir) + "web.xml"), "UTF-8");
                webXmlTemplate.process(root, webXmlOut);

                orgEclipseComponentOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + settingsDir) + "org.eclipse.wst.common.component"),
                        "UTF-8");
                orgEclipseComponentTemplate.process(root, orgEclipseComponentOut);

                manifestmfOut = new OutputStreamWriter(
                        new FileOutputStream(FreeOutUtil.checkAndMakeDir(outPathVal + meta_infDir) + "MANIFEST.MF"),
                        "UTF-8");
                manifestmfTemplate.process(root, manifestmfOut);

            }

            // System.out.println("转换成功");

            pomOut.flush();
            clpassPathOut.flush();
            projectOut.flush();
            castUtilOut.flush();
            homeHtmlOut.flush();
            welcomeHtmlOut.flush();
            /*
             * baseControllerOut.flush(); IBaseServiceOut.flush(); baseServiceOut.flush();
             */
            IBaseDaoOut.flush();
            excelUtilOut.flush();
            logbackOut.flush();
            mybatisConfigOut.flush();
            userControllerOut.flush();
            loginHtmlOut.flush();
            userModelOut.flush();
            allExceptionHandlerOut.flush();
            logAopAspectOut.flush();
            loggerUtilOut.flush();
            commonResultOut.flush();
            resultConstantOut.flush();
            configJsOut.flush();
            commonEntityOut.flush();
            pageDataOut.flush();

            if ("是".equals(ChildWindowConstant.commonParametersModel.getIfUseSwagger())) {
                swaggerConfigOut.flush();
            }

            if ("动态用户".equals(loginModel)) {

                userMapperOut.flush();
                IUserServiceOut.flush();
                userServiceOut.flush();
                IUserDaoOut.flush();
            }

            if ("springBoot".equals(frameWorkVal)) {
                resourcesYmlOut.flush();
                mainApplicationOut.flush();
                mainApplicationTestOut.flush();
                mvcConfigOut.flush();
                transactionAdviceConfigOut.flush();
            }

            if ("ssm".equals(frameWorkVal)) {
                mvcInterceptorOut.flush();
                mvcJdbcPropertiesOut.flush();
                springMvcXmlOut.flush();
                springMybatisOut.flush();
                webXmlOut.flush();
                orgEclipseComponentOut.flush();
                manifestmfOut.flush();
            }

        } catch (
                IOException e)

        {
            e.printStackTrace();
            JOptionPane.showMessageDialog(Constant.frmv, "生成代码时出错！", "错误", JOptionPane.ERROR_MESSAGE);
            return false;

        } catch (
                TemplateException e)

        {
            JOptionPane.showMessageDialog(Constant.frmv, "解析模板文件时出错！", "错误", JOptionPane.ERROR_MESSAGE);
            return false;

        } catch (
                Exception e)

        {
            e.printStackTrace();
            JOptionPane.showMessageDialog(Constant.frmv, "生成代码时出错！", "错误", JOptionPane.ERROR_MESSAGE);
            return false;

        } finally

        {

            // 删除model文件
            ZipUtils.deleteFiles(Constant.modelFiles);

            try {
                if (IUserDaoOut != null) {
                    IUserDaoOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (userServiceOut != null) {
                    userServiceOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (IUserServiceOut != null) {
                    IUserServiceOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (userMapperOut != null) {
                    userMapperOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (swaggerConfigOut != null) {
                    swaggerConfigOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (commonResultOut != null) {
                    commonResultOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (resultConstantOut != null) {
                    resultConstantOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (configJsOut != null) {
                    configJsOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (pageDataOut != null) {
                    pageDataOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (commonEntityOut != null) {
                    commonEntityOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (loggerUtilOut != null) {
                    loggerUtilOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (logAopAspectOut != null) {
                    logAopAspectOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (allExceptionHandlerOut != null) {
                    allExceptionHandlerOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (userModelOut != null) {
                    userModelOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (loginHtmlOut != null) {
                    loginHtmlOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (userControllerOut != null) {
                    userControllerOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (manifestmfOut != null) {
                    manifestmfOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (orgEclipseComponentOut != null) {
                    orgEclipseComponentOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (webXmlOut != null) {
                    webXmlOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (springMybatisOut != null) {
                    springMybatisOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (springMvcXmlOut != null) {
                    springMvcXmlOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (mvcJdbcPropertiesOut != null) {
                    mvcJdbcPropertiesOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (mvcInterceptorOut != null) {
                    mvcInterceptorOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (mybatisConfigOut != null) {
                    mybatisConfigOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (logbackOut != null) {
                    logbackOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (transactionAdviceConfigOut != null) {
                    transactionAdviceConfigOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (excelUtilOut != null) {
                    excelUtilOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (IBaseDaoOut != null) {
                    IBaseDaoOut.close();
                }
            } catch (IOException e) {

            }

            /*
             * try { if (baseServiceOut != null) { baseServiceOut.close(); } } catch
             * (IOException e) {
             *
             * }
             *
             * try { if (IBaseServiceOut != null) { IBaseServiceOut.close(); } } catch
             * (IOException e) {
             *
             * }
             *
             * try { if (baseControllerOut != null) { baseControllerOut.close(); } } catch
             * (IOException e) {
             *
             * }
             */

            try {

                if (mvcConfigOut != null) {
                    mvcConfigOut.close();
                }
            } catch (IOException e) {

            }

            try {

                if (welcomeHtmlOut != null) {
                    welcomeHtmlOut.close();
                }
            } catch (IOException e) {

            }

            try {

                if (homeHtmlOut != null) {
                    homeHtmlOut.close();
                }
            } catch (IOException e) {

            }

            try {

                if (castUtilOut != null) {
                    castUtilOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (mainApplicationTestOut != null) {
                    mainApplicationTestOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (mainApplicationOut != null) {
                    mainApplicationOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (projectOut != null) {
                    projectOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (clpassPathOut != null) {
                    clpassPathOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (pomOut != null) {
                    pomOut.close();
                }
            } catch (IOException e) {

            }

            try {
                if (resourcesYmlOut != null) {
                    resourcesYmlOut.close();
                }
            } catch (IOException e) {

            }

        }
        return true;
    }

    /**
     * 登录用户设置
     *
     * @param loginModel
     * @param root
     */
    private static void setLonginUser(String loginModel, Map<String, Object> root) {

        if ("静态用户".equals(loginModel)) {

            String condition = "";

            if (ChildWindowConstant.user1.size() != 0) {

                condition += "(\"" + ChildWindowConstant.user1.get(0) + "\"" + ".equals(user.getUserName()) && " + "\""
                        + ChildWindowConstant.user1.get(1) + "\"" + ".equals(user.getPassword()))" + " || ";

            }

            if (ChildWindowConstant.user2.size() != 0) {
                condition += "(\"" + ChildWindowConstant.user2.get(0) + "\"" + ".equals(user.getUserName()) && " + "\""
                        + ChildWindowConstant.user2.get(1) + "\"" + ".equals(user.getPassword()))" + " || ";

            }

            if (ChildWindowConstant.user3.size() != 0) {

                condition += "(\"" + ChildWindowConstant.user3.get(0) + "\"" + ".equals(user.getUserName()) && " + "\""
                        + ChildWindowConstant.user3.get(1) + "\"" + ".equals(user.getPassword()))" + " || ";

            }

            condition = condition.substring(0, condition.lastIndexOf("|") - 2);

            root.put(CodeConstant.userCondition, condition);
            root.put(CodeConstant.userNameFiled, "userName");
            root.put(CodeConstant.userPwdFiled, "password");

        } else if ("动态用户".equals(loginModel)) {

            root.put(CodeConstant.userTable, ChildWindowConstant.dynamicUserList.get(0));
            root.put(CodeConstant.userNameFiled, ChildWindowConstant.dynamicUserList.get(1));
            root.put(CodeConstant.userPwdFiled, ChildWindowConstant.dynamicUserList.get(2));

        }
    }

    /**
     * 自定义实体
     *
     * @throws Exception
     */
    private static void getMakeEntity(String outPathVal, String entityDir, Map<String, Object> root) throws Exception {

        // 自定义实体
        if (ChildWindowConstant.makeEntityModelMap.size() == 0) {
            return;
        }

        // 输出流
        Writer makeEntityOut = null;

        try {
            Template makeEntityTemplate = FreeMarkerConfig.configuration.getTemplate(CodeFtlConstant.makeEntity_ftl);
            makeEntityTemplate.setEncoding("UTF-8");

            for (Map.Entry<String, List<MakeEntityModel>> entry : ChildWindowConstant.makeEntityModelMap.entrySet()) {

                String makeEntityName = entry.getKey();

                List<MakeEntityModel> MakeEntityModels = entry.getValue();

                for (MakeEntityModel makeEntityModel : MakeEntityModels) {
                    if ("List".equals(makeEntityModel.getServiceType())) {
                        root.put(CodeConstant.hasList, 1);
                        break;
                    }
                }

                root.put(CodeConstant.makeEntityName, makeEntityName);

                root.put(CodeConstant.MakeEntityModels, MakeEntityModels);

                root.put(CodeConstant.makeEntityName_cn, ChildWindowConstant.makeEntityEngAndCn.get(makeEntityName));

                makeEntityOut = new OutputStreamWriter(new FileOutputStream(
                        FreeOutUtil.checkAndMakeDir(outPathVal + entityDir) + captureName(makeEntityName) + ".java"),
                        "UTF-8");

                makeEntityTemplate.process(root, makeEntityOut);

                root.remove(CodeConstant.hasList);

                makeEntityOut.flush();

            }
        } finally {
            if (makeEntityOut != null) {
                makeEntityOut.close();
            }

        }

    }

    // 首字母大写 驼峰
    private static String captureName(String name) {

        String result = "";

        if (name.contains(".")) {

            String[] nameArr = name.split("\\.");

            for (String str : nameArr) {
                if (str.length() > 1) {
                    result += str.substring(0, 1).toUpperCase() + str.substring(1);
                } else {
                    result += str.substring(0, 1).toUpperCase();
                }
            }
        } else if (name.contains("_")) {
            String[] nameArr = name.split("\\_");

            for (String str : nameArr) {
                if (str.length() > 1) {
                    result += str.substring(0, 1).toUpperCase() + str.substring(1);
                } else {
                    result += str.substring(0, 1).toUpperCase();
                }
            }
        } else if (name.contains("-")) {
            String[] nameArr = name.split("-");

            for (String str : nameArr) {
                if (str.length() > 1) {
                    result += str.substring(0, 1).toUpperCase() + str.substring(1);
                } else {
                    result += str.substring(0, 1).toUpperCase();
                }
            }
        } else {
            if (name.length() > 1) {
                result = name.substring(0, 1).toUpperCase() + name.substring(1);
            } else {
                result = name.substring(0, 1).toUpperCase();
            }

        }

        return result;
        /*
         * char[] cs = name.toCharArray(); cs[0] -= 32; return String.valueOf(cs);
         */

    }

}
